package com.zzyl.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

// java example
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        this.strictInsertFill(metaObject, "createBy", String.class, loadUserId());
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());

        this.strictInsertFill(metaObject, "updateBy", String.class, loadUserId());
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        this.strictInsertFill(metaObject, "updateBy", String.class, loadUserId());
        this.strictUpdateFill(metaObject, "updateTime", Date.class,  new Date());
    }

    public String loadUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
             return loginUser.getUserId().toString();
        } catch (Exception e) {
            return "1";
        }
    }
}
